package com.andnnl.guava;

import com.andnnl.future.ThreadUtil;
import com.google.common.util.concurrent.SimpleTimeLimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenss on 2021/2/25.
 */
public class TimeoutTest {
    public static void main(String[] args) {
       Object rs= guavaTest();
        System.out.println(rs);
    }
    public static Object guavaTest() {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        SimpleTimeLimiter simpLeTimeLimiter = new SimpleTimeLimiter(executorService);
        Object result = "time..";
        try {
            result = simpLeTimeLimiter.callWithTimeout(() -> {
                //超时测试方法
                return timeoutTest();
            }, 2, TimeUnit.SECONDS, true);
        } catch (Exception e) {
            //异常处理,发送报警
            e.printStackTrace();
        } finally {
            //关闭线程
            executorService.shutdown();
        }
        return result;
    }

    private static Object timeoutTest() {
        ThreadUtil.sleep(1000);
        return "ssssssssssssssss";
    }

}
